package com.sitech.ibnms.c3p.command;

import com.sitech.ibnms.c3p.Application;
import com.sitech.ibnms.c3p.domain.C3pCommand;
import com.sitech.ibnms.c3p.mappers.C3pCommandMapper;
import com.sitech.ibnms.c3p.util.C3pConstants;
import com.sitech.ibnms.c3p.util.JSONUtil;
import com.sitech.ismp.workflow.domain.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.util.Assert;

import java.util.HashMap;
import java.util.Map;

/**
 * 指令，任务中的环节
 * Created by liujhc on 7/5.
 */
public abstract class CommandSupport implements Command {

    protected final Logger logger = LoggerFactory.getLogger(getClass());

    private String commandId;
    private Task task;
    private String c3pTaskId;

    @Override
    public abstract CommandType getType();

    @Override
    public void execute(String c3pTaskId, Task task) {
        this.task = task;
        this.c3pTaskId = c3pTaskId;
        doExecute(c3pTaskId, task);
    }

    protected abstract void doExecute(String c3pTaskId, Task task);

    protected Map<String, String> prepareContext(String c3pTaskId, Task task, String resourceId) {
        Map<String, String> context = new HashMap<String, String>();
        context.put(C3pConstants.PARAM_C3P_COMMAND_ID, this.commandId);
        context.put(C3pConstants.PARAM_COMMAND_TYPE, getType().name());
        context.put(C3pConstants.PARAM_C3P_TASK_ID, c3pTaskId);
        context.put(C3pConstants.PARAM_WORKFLOW_TASK, JSONUtil.toJSON(task));
        context.put(C3pConstants.PARAM_EXECUTE_RESOURCE_ID, resourceId);
        return context;
    }

    @Override
    public void setCommandId(String commandId) {
        // 一个指令只能使用一次（scope=prototype）， 如果commandId已经存在，抛出异常
        Assert.isNull(this.commandId, String.format("commandId already exists. Please check %s, it must be singleton!", this.getClass()));
        this.commandId = commandId;
    }

    @Override
    public String getCommandId() {
        return commandId;
    }

    protected String getC3pTaskId() {
        return c3pTaskId;
    }

    protected Task getTask() {
        return task;
    }
//
    public static Command newCommand(String commandId) {
        //查询对应的C3pCommand对象，用beanFactory创建C3pCommand对象，用springBeanFactory创建
        //C3pCommand为配置数据  用AutowireCapableBeanFactory构造出可用的对象
        C3pCommand c3pCommand = Application.getBean(C3pCommandMapper.class).findById(commandId);
        Assert.notNull(c3pCommand, String.format("Can not find C3pCommand by commandId=%s", commandId));
        Assert.notNull(c3pCommand.getCommandType(), String.format("commandType must not be null: %s", c3pCommand));
        AutowireCapableBeanFactory beanFactory = Application.getContext().getAutowireCapableBeanFactory();
        Command command = beanFactory.createBean(c3pCommand.getCommandType().getBeanClass());
        command.setCommandId(commandId);
        return command;
    }
}
